package com.focusai.efairy.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.focusai.efairy.R;
import com.focusai.efairy.business.update.AppUpdateAgent;
import com.focusai.efairy.model.JPushResult;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.user.User;
import com.focusai.efairy.ui.activity.announce.AnnounceDetailActivity;
import com.focusai.efairy.ui.base.BaseFragmentActivity;
import com.focusai.efairy.ui.fragment.AppFragment;
import com.focusai.efairy.ui.fragment.DevFragment;
import com.focusai.efairy.ui.fragment.MoreFragment;
import com.focusai.efairy.ui.fragment.NewFragment;
import com.focusai.efairy.ui.fragment.ProjectFragment;
import com.focusai.efairy.utils.ActivityUtils;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.GsonHelper;
import com.focusai.efairy.utils.JiGuangPushUtil;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class HomeActivity extends BaseFragmentActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rpTab;
    private RadioButton rbDeal, rbPoi, rbMore, rbUser;
    private NewFragment fg1;
    private Fragment fg2;
    private AppFragment fg3;
    private MoreFragment fg4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        bindEvents();
        checkPermission();
        checkPushMsg(getIntent());
        checkAndShowWarmming(AppUpdateAgent.checkAppUpdate(HomeActivity.this, false));
//        Intent intent =  new Intent(getApplication(),PushService.class);
//        startService(intent);
    }

    @Override
    protected void onResume() {
        JiGuangPushUtil.resumePush();
        super.onResume();
    }

    @Override
    protected void initView() {
        rpTab = (RadioGroup) findViewById(R.id.rd_group);
        rbDeal = (RadioButton) findViewById(R.id.rd_menu_deal);
        rbPoi = (RadioButton) findViewById(R.id.rd_menu_poi);
        rbMore = (RadioButton) findViewById(R.id.rd_menu_more);
        rbUser = (RadioButton) findViewById(R.id.rd_menu_user);
    }

    @Override
    protected void bindEvents() {
        rpTab.setOnCheckedChangeListener(this);
        rbDeal.setChecked(true);
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (checkedId) {
            case R.id.rd_menu_deal://消息
                if (fg1 == null) {
                    fg1 = new NewFragment();
                    transaction.add(R.id.fragment_container, fg1);
                } else {
                    transaction.show(fg1);
                }

                break;
            case R.id.rd_menu_poi://设备
                if (fg2 == null) {
                    //1.2.1改为不管什么用户都从项目列表进入设备列表，所以注释了
//                    if (CacheManager.getUserRoleLevel() == User.NORMALUSER) {
//                        fg2 = new DevFragment();
//                        Bundle bundle = new Bundle();
//                    } else {
                        fg2 = new ProjectFragment();
//                    }
                    transaction.add(R.id.fragment_container, fg2);
                } else {
                    transaction.show(fg2);
                }

                break;
            case R.id.rd_menu_more://应用
                if (fg3 == null) {
                    fg3 = new AppFragment();
                    transaction.add(R.id.fragment_container, fg3);
                } else {
                    transaction.show(fg3);
                }

                break;
            case R.id.rd_menu_user://更多
                if (fg4 == null) {
                    fg4 = new MoreFragment();
                    transaction.add(R.id.fragment_container, fg4);
                } else {
                    transaction.show(fg4);
                }

                break;
        }
        transaction.commit();
    }

    public void hideAllFragment(FragmentTransaction transaction) {
        if (fg1 != null) {
            transaction.hide(fg1);
        }
        if (fg2 != null) {
            transaction.hide(fg2);
        }
        if (fg3 != null) {
            transaction.hide(fg3);
        }
        if (fg4 != null) {
            transaction.hide(fg4);
        }
    }

    private long mBackKeyDownTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (rbPoi.isChecked()) {
                if ((fg2 instanceof DevFragment && ((DevFragment) fg2).onKeyDown(keyCode, event))
                        || (fg2 instanceof ProjectFragment && ((ProjectFragment) fg2).onKeyDown(keyCode, event))) {
                    return true;
                }
            }
            if (System.currentTimeMillis() - mBackKeyDownTime <= 2000) {
//                moveTaskToBack(true);
                finish();
            } else {
                Toast.makeText(this, getString(R.string.exit_back_key_down_again), Toast.LENGTH_SHORT).show();
            }
            mBackKeyDownTime = System.currentTimeMillis();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        checkPushMsg(intent);
    }

    private void checkPushMsg(Intent intent) {
        if (intent != null && intent.getBooleanExtra(Constants.CHECK, false)) {
            String msg = intent.getStringExtra(Constants.PUSH_MSG);
            JPushResult result = GsonHelper.getInstance().fromJson(msg, new TypeToken<JPushResult>() {
            }.getType());
            if (result != null && result.efairy != null && result.efairy.id > 0) {
                if (result.efairy.type == 0) {
                    Intent intent1 = new Intent(getContext(), AnnounceDetailActivity.class);
                    intent1.putExtra(AnnounceDetailActivity.KEY_ANNOUNCE_ID, result.efairy.id);
                    startActivity(intent1);
                } else if (result.efairy.type == 1) {
                    showMsgDialog((int) result.efairy.id);
                }
            }
        }
    }

    private void showMsgDialog(int roleId) {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        final boolean isSameRole = (roleId == CacheManager.getUserRoleLevel());
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (isSameRole) {
                    ActivityUtils.cleanAndStartLoginActivity(HomeActivity.this);
                    finish();
                }
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancal), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setCancelable(true);

        String string = "";
        if (isSameRole) {
            string = "您的角色变更为" + User.getRoleName(roleId) + ",需要重新登录";
        } else {
            string = "恭喜您的角色已为" + User.getRoleName(roleId);
        }
        dialog.setMessage(string);
        dialog.show();
    }

    private void checkPermission() {
        checkPermission(PermissionUtil.PERMISSION_STORAGE, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {

            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {
                showToast("应用没写SD卡权限");
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 显示用户告警书
     */
    private void checkAndShowWarmming(final int versionCode) {
        if (versionCode > CacheManager.getLastVersionCode()) {
            AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
            dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.has_readed), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    CacheManager.setLastVersionCode(versionCode);
                }
            });

            dialog.setCancelable(false);
//            dialog.setMessage(getString(R.string.warnning_user));
            dialog.setView(LayoutInflater.from(getContext()).inflate(R.layout.view_user_warn_dialog, null));
            dialog.show();
        }
    }
}